<template>
    <div
        style="padding-top: 40px"
        v-loading="pageLoading"
        element-loading-text="正在加载,请稍等"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
    >
        <el-form style="margin: 1px 10px 30px 30px" :model="dataForm" ref="dataForm" label-width="80px">
            <el-row>
                <el-col :span="10">
                    <el-form-item label="公司名称">
                        <el-input v-model="dataForm.companyName" placeholder=""  clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="10">
                    <el-form-item label="联系人">
                        <el-input v-model="dataForm.linkman" placeholder=""  clearable> </el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="10">
                    <el-form-item label="联系电话">
                        <el-input
                            v-model="dataForm.telephone"
                            placeholder=""
                            clearable
                            oninput="value=value.replace(/[^\d]/g,'')"
                            maxlength="11"
                        ></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="10">
                    <el-form-item label="邮箱">
                        <el-input v-model="dataForm.email" placeholder=""  clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="10">
                    <el-form-item label="联系地址">
                        <el-input v-model="dataForm.address" :placeholder="addrPlaceholder" :disabled="addrDisabled"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="16">
                    <!-- 百度地图  -->
                    <baidu-map
                        :center="center"
                        :zoom="zoom"
                        @ready="handler"
                        style="height: 360px; margin: 10px 80px"
                        @click="getClickInfo"
                        :scroll-wheel-zoom="true"
                    >
                        <!-- 定位 -->
                        <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>

                        <!-- 自定义搜索框 -->
                        <bm-control style="margin: 15px" v-if="isVisible">
                            <el-input v-model="inputSearchAddr" placeholder="搜索地址" style="height: 100px; width: 400px"></el-input>
                            <el-button type="primary" @click="searchClick()" style="margin-left: 10px">搜索</el-button>
                            <el-button type="primary" @click="enterAddrClick()" style="margin-left: 10px">手动输入地址</el-button>
                        </bm-control>

                        <!-- bm-local-search是自带的搜索功能,双向绑定 keyword 可以进行搜索 -->
                        <bm-local-search
                            :keyword="searchAddr"
                            :auto-viewport="false"
                            :selectFirstResult="true"
                            :location="location"
                            :panel="true"
                            v-on:searchcomplete="searchComplete"
                            style="display: none"
                        >
                        </bm-local-search>
                    </baidu-map>
                </el-col>
            </el-row>
        </el-form>

        <span slot="footer" style="margin: 30px 10px 30px 60px" class="dialog-footer">
            <el-button type="primary" @click="dataFormSubmit()">保存</el-button>
            <el-button @click="closePage()">取消</el-button>
        </span>
    </div>
</template>
<script>
import API from '@/api';
import cloneDeep from 'lodash/cloneDeep';
import { BmLocalSearch } from 'vue-baidu-map';

export default {
    components: {
        BmLocalSearch
    },
    data() {
        return {
            typeOptions: [],
            pageLoading: false,
            dataForm: {
                companyName: '', //公司名称
                linkman: '', //联系人
                telephone: '', //联系电话
                email: '', //邮箱
                address: '', //联系地址
                longitude: 0, //经度
                latitude: 0 //纬度
            },
            center: { lng: 0, lat: 0 },
            zoom: 3,
            inputSearchAddr: '',
            location: '',
            searchAddr: '',
            loading: false,
            addrDisabled: true,
            addrPlaceholder: '请在地图上选择地址',
            isVisible: false //是否可见
        };
    },
    mounted() {
        this.getDetail(); //获取关于我们信息
    },

    methods: {
        getDetail() {
            API.aboutUsInfoManger.getAboutUsDetail().then((res) => {
                if (res.code == '0000') {
                    console.log(res);
                    this.dataForm = res.result;
                }
            });
        },

        //百度地图
        handler({ BMap, map }) {
            this.map = map;

            //自动定位设置中心点
            let _this = this;
            var geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(
                function (r) {
                    console.log(r);
                    if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                        _this.center = { lng: r.longitude, lat: r.latitude };
                        _this.zoom = 17;

                        var translateCallback = function (data) {
                            //坐标转换完之后的回调函数
                            console.log(data);
                            console.log(data.status);
                            if (data.status === 0) {
                                if (_this.dataForm.address !== '') {
                                    //编辑
                                    var point = new BMap.Point(_this.dataForm.longitude, _this.dataForm.latitude);
                                    var marker = new BMap.Marker(point);
                                    map.addOverlay(marker);
                                    var label = new BMap.Label('公司位置', { offset: new BMap.Size(20, -10) });
                                    marker.setLabel(label); //添加百度label
                                    map.setCenter(point);
                                    _this.zoom = 17;
                                } else {
                                    //其他

                                    var marker = new BMap.Marker(data.points[0]);
                                    map.addOverlay(marker);
                                    var label = new BMap.Label('当前我的定位', { offset: new BMap.Size(20, -10) });
                                    marker.setLabel(label); //添加百度label
                                    map.setCenter(data.points[0]);
                                }

                                _this.isVisible = true;
                            }
                        };

                        setTimeout(() => {
                            var convertor = new BMap.Convertor();
                            var pointArr = [];

                            var ggPoint = new BMap.Point(_this.center.lng, _this.center.lat);
                            pointArr.push(ggPoint);
                            convertor.translate(pointArr, 1, 5, translateCallback);
                        }, 1000);
                    } else {
                        console.log('map location failed', this.getStatus());
                    }
                },
                { enableHighAccuracy: true }
            );

            // 添加鼠标滚动缩放
            map.enableScrollWheelZoom();

            // 添加缩放平移控件
            map.addControl(new BMap.NavigationControl({ isOpen: false, anchor: BMAP_ANCHOR_TOP_RIGHT }));

            //添加比例尺控件
            map.addControl(new BMap.ScaleControl());
        },

        getClickInfo(e) {
            console.log('点击的地图位置信息：', e);

            //移动地图中心位置
            this.center.lng = e.point.lng;
            this.center.lat = e.point.lat;
            this.zoom = e.target.getZoom();

            //清空标记
            this.map.clearOverlays();

            // 利用坐标获取地址的详细信息
            let geoCoder = new BMap.Geocoder();
            geoCoder.getLocation(e.point, (res) => {
                console.log('获取的搜索地址：', res);
                let addr = res.address;

                if (res.surroundingPois.length > 0) {
                    addr = addr + res.surroundingPois[0].title;

                    this.dataForm.address = addr;
                    this.dataForm.longitude = res.surroundingPois[0].point.lng;
                    this.dataForm.latitude = res.surroundingPois[0].point.lat;

                    //重绘标记
                    var mk = new BMap.Marker(res.surroundingPois[0].point);
                    this.map.addOverlay(mk);
                    this.searchAddr = '';
                } else {
                    this.dataForm.address = addr;
                    this.dataForm.longitude = e.point.lng;
                    this.dataForm.latitude = e.point.lat;

                    //重绘标记
                    var mk = new BMap.Marker(e.point);
                    this.map.addOverlay(mk);
                    this.searchAddr = '';
                }
            });
        },

        //地图 搜索点击
        searchClick() {
            this.addrDisabled = true;
            this.addrPlaceholder = '请在地图上选择地址';
            if (this.inputSearchAddr === '') {
                this.$message({
                    message: `请输入搜索地址`,
                    type: 'success'
                });

                return;
            }

            this.loading = true;
            this.searchAddr = this.inputSearchAddr;

            //最多60秒，不等完成 要消失
            setTimeout(() => {
                this.loading = false;
            }, 600000);
        },

        searchComplete(val) {
            this.loading = false;
            console.log('搜索完成监听：', val);
            if (val != null && val.Hr != null && val.Hr.length > 0) {
                // 利用坐标获取地址的详细信息
                let geoCoder = new BMap.Geocoder();
                geoCoder.getLocation(val.Hr[0].point, (res) => {
                    console.log('获取的搜索地址：', res);
                    let addr = res.address;

                    if (res.surroundingPois.length > 0) {
                        addr = addr + res.surroundingPois[0].title;

                        this.dataForm.address = addr;
                        this.dataForm.longitude = res.surroundingPois[0].point.lng;
                        this.dataForm.latitude = res.surroundingPois[0].point.lat;
                    } else {
                        this.dataForm.address = addr;
                        this.dataForm.longitude = e.point.lng;
                        this.dataForm.latitude = e.point.lat;
                    }
                });
            }
        },

        //手动输入地址
        enterAddrClick() {
            this.addrDisabled = false;
            this.addrPlaceholder = '手动输入的地址，地图上会正常显示';
            this.$message({
                message: `手动输入的地址，地图上会无法正常显示`,
                type: 'success'
            });
        },

        //- 保存
        dataFormSubmit() {
            let params = cloneDeep(this.dataForm);

            API.aboutUsInfoManger.aboutUsUpdate(params).then((data) => {
                if (data.code == '0000') {
                    this.$message({
                        message: '操作成功',
                        type: 'success',
                        duration: 1500,
                        onClose: () => {
                            this.closePage();
                        }
                    });
                }
            });
        },
        closePage() {
            this.$router.go(-1);
        }
    }
};
</script>